package cn.com.dashihui.web.common;

import com.jfinal.plugin.ehcache.CacheKit;

import cn.com.dashihui.kit.CommonKit;


public class CacheHolder {
	private static final String CACHE_COMMON = "CommonCache";
	public static final String NAVMENUS = "navMenusStore";
	public static final String USERPOPEDOM = "userpopedomStore";
	
	public static void cache(String key, Object value){
		cacheTo(CACHE_COMMON, key, value);
	}
	
	public static void cache(String cachename, String key, Object value){
		cacheTo(cachename, key, value);
	}
	
	public static void cache(String key, Object value, long time){
		cacheTo(CACHE_COMMON, key, value);
		if(time!=0){
			cacheTo(CACHE_COMMON, key(key,"from"), System.currentTimeMillis());
			cacheTo(CACHE_COMMON, key(key,"time"), time);
		}
	}
	
	public static void cache(String cachename, String key, Object value, long time){
		cacheTo(CACHE_COMMON, key, value);
		if(time!=0){
			cacheTo(cachename, key(key,"from"), System.currentTimeMillis());
			cacheTo(cachename, key(key,"time"), time);
		}
	}
	
	public static void cacheTo(String cachename, String key, Object value){
		CacheKit.put(cachename, key, value);
	}
	
	public static boolean has(String key){
		return get(key)!=null;
	}
	
	public static boolean has(String cachename, String key){
		return get(cachename,key)!=null;
	}
	
	public static Object get(String key){
		return getFrom(CACHE_COMMON, key);
	}
	
	public static Object get(String cachename, String key){
		return getFrom(cachename, key);
	}
	
	public static String getStr(String key){
		return String.valueOf(get(key));
	}
	
	public static String getStr(String cachename, String key){
		return String.valueOf(get(cachename,key));
	}
	
	public static int getInt(String key){
		return Integer.valueOf(String.valueOf(get(key)));
	}
	
	public static int getInt(String cachename, String key){
		return Integer.valueOf(String.valueOf(get(cachename,key)));
	}
	
	public static Object getFrom(String cachename, String key){
		Object value = CacheKit.get(cachename, key);
		Long from = CacheKit.get(cachename, key(key,"from"));
		Long time = CacheKit.get(cachename, key(key,"time"));
		if(from!=null&&from!=0&&time!=null&&time!=0){
			long to = System.currentTimeMillis();
			if(to-from>time){
				return null;
			}
		}
		return value;
	}
	
	/**
	 * 移除缓存
	 */
	public static void remove(String key){
		CacheKit.remove(CACHE_COMMON, key);
	}
	
	/**
	 * 移除缓存
	 */
	public static void remove(String cachename, String key){
		CacheKit.remove(cachename, key);
	}
	
	/**
	 * 根据入参，生成以冒号分隔的字符串，可以用来作为Cache的Key
	 * @param strs
	 * @return
	 */
	public static String key(String... strs){
		return CommonKit.join(":",strs);
	}
	
}
